package com.zhanggm.springcloud.order.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.zhanggm.springcloud.common.Order;
import com.zhanggm.springcloud.order.service.OrderService;
import com.zhanggm.springcloud.user.api.UserApi;
import com.zhanggm.springcloud.user.api.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
@RequestMapping("/order/")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private UserApi userApi;

    /**
     * 根据订单id,查询订单信息
     * @param id
     * @return
     */
    @GetMapping("getById")
    public Order getOrderById(@RequestParam("id") Integer id){
        Order order = orderService.getById(id);
        //服务间调用，查询用户信息
        Integer userId = order.getUserId();
        User user = userApi.getUserById(userId);
        order.setUsername(user.getUsername());
        return  order;
    }

    @GetMapping("getOrder")
    @HystrixCommand(fallbackMethod = "getOrderFallback")
    public Order getOrder(Integer id){
        //服务间调用，查询用户信息
        Order order = orderService.getById(id);
//        User user = userApi.getUserById(order.getUserId());
        User u = new User();
        u.setId(order.getUserId());
        User user = userApi.getUserByUser(u);
        order.setUsername(user.getUsername());
        return order;
    }

    public Order getOrderFallback(Integer id){
        Order order = new Order();
        order.setUsername("error");
        return order;
    }

}
